#include "buffer.h"


void buffer_init(Buffer* buf) {
    buf->data = NULL;
    buf->len = 0;
    buf->cap = 0;
}


void buffer_free(Buffer* buf) {
    if(buf->data != NULL) free(buf->data);
    buf->data = NULL;
    buf->len = buf->cap = 0;
}


void buffer_clear(Buffer* buf) {
    //分配的内存不释放,只清空所存内容
    buf->len = 0;
}


// const char* buffer_data(const Buffer* buf) {
//     return buf->data != NULL ? buf->data : "";
// }


// size_t buffer_len(const Buffer* buf) {
//     return buf->len;
// }

int buffer_grow(Buffer* buf, size_t need) {
    //指数增长：至少翻倍,直到满足需求或达到上限
    size_t new_cap = buf->cap ? buf->cap * 2 : BUFFER_INIT_CAP;
    
    while (new_cap < buf->len + need) {
        if (new_cap >= BUFFER_MAX_CAP / 2) {
            new_cap = BUFFER_MAX_CAP;
            break;
        }
        new_cap *= 2;
    }
    
    if(new_cap < buf->len + need) return 0; //超过最大限制
    
    char* new_data = realloc(buf->data,new_cap);
    if(!new_data) return 0;
    
    buf->data = new_data;
    buf->cap = new_cap;
    return 1;
}


int buffer_append(Buffer* buf,char* data,size_t len){
    if(len == 0) return 1;
    
    if(buf->len + len > buf->cap){
        if(!buffer_grow(buf, len)) return 0;
    }
    
    memcpy(buf->data + buf->len,data,len);
    buf->len += len;
    return 1;
}

